package com.huizluo.module4.chatroom;

import java.io.*;
import java.net.Socket;

public class MsgRevc implements Runnable {
    private Socket socket;

    public MsgRevc(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        ObjectInputStream oip = null;
        try {
            System.out.println("client 准备接收消息");
            while (true){
                oip = new ObjectInputStream(this.socket.getInputStream());
                Message message = (Message)oip.readObject();
                System.out.println("接收到消息:" + new String(message.getData()));
                if (message.getType() == 1){
                    this.recvFile();
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (oip != null){
                try {
                    oip.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    void recvFile(){
        DataInputStream dis = null;
        FileOutputStream fo = null;
        try {
            dis = new DataInputStream(this.socket.getInputStream());
            String fileName = dis.readUTF();
            long len = dis.readLong();

            File file = new File("/tmp/filetest/"+fileName);
            file.createNewFile();

            fo = new FileOutputStream(file);

            byte[] bytes = new byte[8*1024];
            int length = 0;
            while ((length = dis.read(bytes,0,bytes.length))!=-1){
                fo.write(bytes,0,length);
                fo.flush();
            }

            System.out.println("文件接收成功 【"+file + " ]");

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (dis!=null){
                    dis.close();
                }
                if (fo!=null){
                    fo.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
